package com.alibaba.citrus.cr.unified.inventory.facade.service;

import com.alibaba.citrus.cr.unified.inventory.repository.EsAllocateApplyOrderIndexRepository;
import com.alibaba.citrus.cr.unified.inventory.utils.InfoUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcorder.platform_enhance.SaleOrderTag;
import com.epoch.app.crb2btradecenter.api.orderlinequery.service.OrderLineQueryService;
import com.epoch.app.crb2btradecenter.dto.response.OrderLinePageQueryResponse;
import com.epoch.app.crb2btradecenter.model.dto.PageQueryOrderLineESListRequest;
import com.epoch.app.crunifiedinventory.api.allocateapplyorderread.service.AllocateApplyOrderReadService;
import com.epoch.app.crunifiedinventory.api.allocateorderread.service.AllocateOrderReadService;
import com.epoch.app.crunifiedinventory.dto.request.AllocateOrderDetailSearchRequest;
import com.epoch.app.crunifiedinventory.dto.response.AllocateApplyOrderListDTO;
import com.epoch.app.crunifiedinventory.dto.response.AllocateOrderDetailVO;
import com.epoch.app.crunifiedinventory.model.dto.*;
import com.epoch.app.crunifiedinventory.model.enums.OrderCompareTypeEnum;
import com.epoch.app.crunifiedinventory.ordercompare.dto.*;
import com.epoch.app.crunifiedinventory.ordercompare.service.OrderCompareService;
import com.epoch.app.crunifiedinventory.ouiordercomparedetail.model.OuiOrderCompareDetail;
import com.epoch.app.crunifiedinventory.ouiordercomparedetail.service.OuiOrderCompareDetailService;
import com.epoch.app.crunifiedinventory.ouiordercomparerecord.dto.CreateResponse;
import com.epoch.app.crunifiedinventory.ouiordercomparerecord.model.OuiOrderCompareRecord;
import com.epoch.app.crunifiedinventory.ouiordercomparerecord.service.OuiOrderCompareRecordService;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import javax.annotation.Nonnull;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.alibaba.citrus.cr.unified.inventory.contants.AllocateDetailObjectCompareUtil.compareTwoClass;
import static com.alibaba.citrus.cr.unified.inventory.contants.SaleDetailObjectCompareUtil.compareTwoClassForSale;

@Service
@Primary
public class OrderCompareServiceImpl implements OrderCompareService {
    public static final String SHIP_RETURN_TYPE = "物流退货订单";
    public static final String NYK_PLAN_FLAG = "nykPlan";
    @Resource
    private OuiOrderCompareRecordService compareRecordService;
    @Resource
    private OuiOrderCompareDetailService compareDetailService;
    @Resource
    private AllocateOrderReadService allocateOrderReadService;
    @Resource
    private EsAllocateApplyOrderIndexRepository esAllocateApplyOrderIndexRepository;
    @Resource
    private OrderLineQueryService orderLineQueryService;

    private static final int querySize = 500;

    private static final List<String> returnOrderType = Lists.newArrayList("ZRE3", "ZRE2", "ZRE5");
    private static final String returnKeywordText = "退货";

    @Override
    public OrderCompareSalesResponse orderCompareSales(OrderCompareSalesRequest orderCompareSalesRequest) {
        if (Objects.isNull(orderCompareSalesRequest) || CollectionUtils.isEmpty(orderCompareSalesRequest.getRequest())) {
            return OrderCompareSalesResponse.builder().success(Boolean.FALSE).message("导入数据不能为空!").build();
        }
        //step 1,insert record
        OuiOrderCompareRecord ouiOrderCompareRecord = new OuiOrderCompareRecord();
        ouiOrderCompareRecord.setCompareCount(orderCompareSalesRequest.getRequest().size());
        ouiOrderCompareRecord.setCompareType(OrderCompareTypeEnum.SALE_ORDER.getValue());
        ouiOrderCompareRecord.setSuccessCount(0);
        CreateResponse createResponse = compareRecordService.create(ouiOrderCompareRecord);

        //step 2,prepara data
        preparaSaleData(orderCompareSalesRequest.getRequest());

        //step 3,do diff, request is SAP order,need compare with ots order
        Integer successCount = doSaleOrderDiff(orderCompareSalesRequest.getRequest(), createResponse.getId());

        //step 4,modify success count for record
        ouiOrderCompareRecord.setId(createResponse.getId());
        ouiOrderCompareRecord.setSuccessCount(successCount);
        ouiOrderCompareRecord.setGmtModified(new Date());
        compareRecordService.update(ouiOrderCompareRecord);

        return OrderCompareSalesResponse.builder().success(Boolean.TRUE).result(orderCompareSalesRequest.getRequest()).build();
    }

    @Override
    public OrderCompareAllocateResponse orderCompareAllocate(OrderCompareAllocateRequest orderCompareAllocateRequest) {
        if (Objects.isNull(orderCompareAllocateRequest) || CollectionUtils.isEmpty(orderCompareAllocateRequest.getRequest())) {
            return OrderCompareAllocateResponse.builder().success(Boolean.FALSE).message("导入数据不能为空!").build();
        }
        //step 1,insert record
        OuiOrderCompareRecord ouiOrderCompareRecord = new OuiOrderCompareRecord();
        ouiOrderCompareRecord.setCompareCount(orderCompareAllocateRequest.getRequest().size());
        ouiOrderCompareRecord.setCompareType(OrderCompareTypeEnum.ALLOCATE_ORDER.getValue());
        ouiOrderCompareRecord.setSuccessCount(0);
        CreateResponse createResponse = compareRecordService.create(ouiOrderCompareRecord);

        //step 2,prepare data
        prepareAllocateData(orderCompareAllocateRequest.getRequest());

        //step 3,do diff, request is SAP order,need compare with ots order
        Integer successCount = doAllocateOrderDiff(orderCompareAllocateRequest.getRequest(), createResponse.getId());


        //step 4,modify success count for record
        ouiOrderCompareRecord.setId(createResponse.getId());
        ouiOrderCompareRecord.setSuccessCount(successCount);
        ouiOrderCompareRecord.setGmtModified(new Date());
        compareRecordService.update(ouiOrderCompareRecord);


        return OrderCompareAllocateResponse.builder().success(Boolean.TRUE).result(orderCompareAllocateRequest.getRequest()).build();
    }

    @Override
    public OrderCompareApplyAllocateResponse orderCompareApplyAllocate(OrderCompareApplyAllocateRequest orderCompareApplyAllocateRequest) {
        if (Objects.isNull(orderCompareApplyAllocateRequest) || CollectionUtils.isEmpty(orderCompareApplyAllocateRequest.getRequest())) {
            return OrderCompareApplyAllocateResponse.builder().success(Boolean.FALSE).message("导入数据不能为空!").build();
        }
        //step 1,insert record
        OuiOrderCompareRecord ouiOrderCompareRecord = new OuiOrderCompareRecord();
        ouiOrderCompareRecord.setCompareCount(orderCompareApplyAllocateRequest.getRequest().size());
        ouiOrderCompareRecord.setCompareType(OrderCompareTypeEnum.APPLY_ALLOCATE_ORDER.getValue());
        ouiOrderCompareRecord.setSuccessCount(0);
        CreateResponse createResponse = compareRecordService.create(ouiOrderCompareRecord);

        //step 2,prepare data
        //prepareAllocateData(orderCompareApplyAllocateRequest.getRequest());

        //step 3,do diff, request is SAP order,need compare with ots order
        Integer successCount = doApplyAllocateOrderDiff(orderCompareApplyAllocateRequest.getRequest(), createResponse.getId());


        //step 4,modify success count for record
        ouiOrderCompareRecord.setId(createResponse.getId());
        ouiOrderCompareRecord.setSuccessCount(successCount);
        ouiOrderCompareRecord.setGmtModified(new Date());
        compareRecordService.update(ouiOrderCompareRecord);


        return OrderCompareApplyAllocateResponse.builder().success(Boolean.TRUE).result(orderCompareApplyAllocateRequest.getRequest()).build();
    }

    @Override
    public OrderCompareAllocateNykResponse orderCompareAllocateNyk(OrderCompareAllocateNykRequest orderCompareAllocateNykRequest) {
        if (Objects.isNull(orderCompareAllocateNykRequest) || CollectionUtils.isEmpty(orderCompareAllocateNykRequest.getRequest())) {
            return OrderCompareAllocateNykResponse.builder().success(Boolean.FALSE).message("导入数据不能为空!").build();
        }
        //step 1,insert record
        OuiOrderCompareRecord ouiOrderCompareRecord = new OuiOrderCompareRecord();
        ouiOrderCompareRecord.setCompareCount(orderCompareAllocateNykRequest.getRequest().size());
        ouiOrderCompareRecord.setCompareType(OrderCompareTypeEnum.NYK_ALLOCATE_ORDER.getValue());
        ouiOrderCompareRecord.setSuccessCount(0);
        CreateResponse createResponse = compareRecordService.create(ouiOrderCompareRecord);

        //step 2,prepare data
        //prepareAllocateData(orderCompareApplyAllocateRequest.getRequest());

        //step 3,do diff, request is SAP order,need compare with ots order
        Integer successCount = doNykAllocateOrderDiff(orderCompareAllocateNykRequest.getRequest(), createResponse.getId());


        //step 4,modify success count for record
        ouiOrderCompareRecord.setId(createResponse.getId());
        ouiOrderCompareRecord.setSuccessCount(successCount);
        ouiOrderCompareRecord.setGmtModified(new Date());
        compareRecordService.update(ouiOrderCompareRecord);


        return OrderCompareAllocateNykResponse.builder().success(Boolean.TRUE).result(orderCompareAllocateNykRequest.getRequest()).build();
    }


    private Integer doSaleOrderDiff(@NotNull List<SalesOrderCompareRequestVO> request, Long recordId) {
        //success count ,init zero success
        int successCount = 0;

        //collection to be compared code list
        List<String> sapCodeList = request.stream().map(SalesOrderCompareRequestVO::getSapSaleOrderId).filter(StringUtils::isNotBlank).distinct().collect(Collectors.toList());
        List<OrderLinePageQueryResponse> orderLineList = new ArrayList<>();
        int idListSize = sapCodeList.size();
        //因为ids入参元素过多，可能造成es查询条件太多而报错，对ID进行分片分批查询
        int idListPage = (idListSize % 1000) > 0 ? (idListSize / 1000 + 1) : idListSize / 1000;

        for (int i = 0; i < idListPage; i++) {
            List<String> pageSapCodeList = (i == idListPage - 1) ? sapCodeList.subList(i * 1000, sapCodeList.size()) : sapCodeList.subList(i * 1000, (i + 1) * 1000);
            PageQueryOrderLineESListRequest pageQueryOrderLineESListRequest = new PageQueryOrderLineESListRequest();
            pageQueryOrderLineESListRequest.setOuterIdLIst(pageSapCodeList);
            pageQueryOrderLineESListRequest.setStart(0);
            pageQueryOrderLineESListRequest.setLimit(querySize);
            Result<List<OrderLinePageQueryResponse>> pageQueryES = orderLineQueryService.pageQueryES(pageQueryOrderLineESListRequest);
            if (Objects.isNull(pageQueryES) || CollectionUtils.isEmpty(pageQueryES.getResult())) {
//                List<SalesOrderCompareRequestVO> noExistOrderList = request.stream().filter(o -> pageSapCodeList.contains(o.getSapSaleOrderId())).collect(Collectors.toList());
//                noExistOrderList.forEach(requestVO -> buildErrorDetail(recordId, requestVO, null, "OTS没有此订单存在!")
//                );
                continue;
            }
            //pull all order list
            orderLineList.addAll(pageQueryES.getResult());
            int total = pageQueryES.getTotal();
            if (total > querySize) {
                int page = ((total % querySize) > 0) ? ((total / querySize) + 1) : (total / querySize);
                for (int j = 1; j < page; j++) {
                    pageQueryOrderLineESListRequest.setStart(j * querySize);
                    List<OrderLinePageQueryResponse> pageResult = orderLineQueryService.pageQueryES(pageQueryOrderLineESListRequest).getResult();
                    orderLineList.addAll(pageResult);
                }
            }
        }

        if (CollectionUtils.isEmpty(orderLineList)) {
            request.forEach(requestVO -> buildErrorDetail(recordId, requestVO, null, "OTS没有此订单存在!"));
            return 0;
        }

        //process result data,some data format
        processSaleResult(orderLineList);

        //db exist sale order ,group by sap out code and line id
        Map<String, List<OrderLinePageQueryResponse>> existOrderMap = orderLineList.stream().collect(Collectors.groupingBy(o -> o.getSapSaleOrderId() + "-" + o.getOutLineId()));

        for (SalesOrderCompareRequestVO requestVO : request) {
            String sapSaleOrderId = requestVO.getSapSaleOrderId();
            //delete prefix zero
            String outLineId = InfoUtil.deleteZeroPrefix(requestVO.getOutLineId());
            List<OrderLinePageQueryResponse> saleOrderDetails = existOrderMap.get(sapSaleOrderId + "-" + outLineId);
            if (CollectionUtils.isEmpty(saleOrderDetails)) {
                buildErrorDetail(recordId, requestVO, null, "OTS没有此订单存在!");
                continue;
            }
            OrderLinePageQueryResponse saleOrderLine = saleOrderDetails.get(0);
            Boolean shouldPersistence = doSaleDiff(recordId, requestVO, saleOrderLine);
            if (shouldPersistence) {
                successCount++;
            }

        }


        return successCount;
    }

    private Boolean doSaleDiff(Long recordId, SalesOrderCompareRequestVO requestVO, OrderLinePageQueryResponse saleOrderLine) {
        try {
            List<OrderCompareErrorResult> results = compareTwoClassForSale(requestVO, saleOrderLine);
            if (CollectionUtils.isEmpty(results)) {
                return true;
            }
            //reduction request object ,for amount format,to the origin import that
            reductionImportObject(requestVO);
            String errorMessage = packageErrorMessage(results);
            buildErrorDetail(recordId, requestVO, saleOrderLine, errorMessage);
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            buildErrorDetail(recordId, requestVO, saleOrderLine, "对账异常:" + e.getMessage());
            return false;
        }
    }

    private Integer doAllocateOrderDiff(@NotNull List<OrderCompareAllocateRequestVO> request, Long recordId) {
        //success count ,init zero success
        int successCount = 0;
        //collection to be compared code list
        List<String> sapCodeList = request.stream().map(OrderCompareAllocateRequestVO::getOutAllocateOrderId).filter(StringUtils::isNotBlank).distinct().collect(Collectors.toList());
        List<AllocateOrderDetailVO> allocateOrderDetailVOList = new ArrayList<>();
        int idListSize = sapCodeList.size();
        //因为ids入参元素过多，可能造成es查询条件太多而报错，对ID进行分片分批查询
        int idListPage = (idListSize % 1000) > 0 ? (idListSize / 1000 + 1) : idListSize / 1000;
        for (int i = 0; i < idListPage; i++) {
            List<String> pageSapCodeList = (i == idListPage - 1) ? sapCodeList.subList(i * 1000, sapCodeList.size()) : sapCodeList.subList(i * 1000, (i + 1) * 1000);

            AllocateOrderDetailSearchRequest allocateOrderDetailSearchRequest = new AllocateOrderDetailSearchRequest();
            allocateOrderDetailSearchRequest.setOutAllocateOrderIds(pageSapCodeList);
            allocateOrderDetailSearchRequest.setStart(0);
            allocateOrderDetailSearchRequest.setLimit(querySize);
            Result<List<AllocateOrderDetailVO>> searchRepones = allocateOrderReadService.search(allocateOrderDetailSearchRequest);
            if (Objects.isNull(searchRepones) || CollectionUtils.isEmpty(searchRepones.getResult())) {
                continue;
            }
            //pull all order list
            allocateOrderDetailVOList.addAll(searchRepones.getResult());
            int total = searchRepones.getTotal();
            if (total > querySize) {
                int page = ((total % querySize) > 0) ? ((total / querySize) + 1) : (total / querySize);
                for (int j = 1; j < page; j++) {
                    allocateOrderDetailSearchRequest.setStart(j * querySize);
                    List<AllocateOrderDetailVO> pageResult = allocateOrderReadService.search(allocateOrderDetailSearchRequest).getResult();
                    allocateOrderDetailVOList.addAll(pageResult);
                }
            }
        }

        if (CollectionUtils.isEmpty(allocateOrderDetailVOList)) {
            request.forEach(requestVO -> buildErrorDetail(recordId, requestVO, null, "OTS没有此订单存在!")
            );
            return 0;
        }

        //process database result
        processAllocateResult(allocateOrderDetailVOList);
        //db exist allocate order ,group by sap out code and line id
        Map<String, List<AllocateOrderDetailVO>> existOrderMap = allocateOrderDetailVOList.stream().collect(Collectors.groupingBy(o -> o.getOutAllocateOrderId() + "-" + o.getOutAllocateOrderLineId()));

        for (OrderCompareAllocateRequestVO requestVO : request) {
            String outAllocateOrderId = requestVO.getOutAllocateOrderId();
            //delete prefix zero
            String outLineId = InfoUtil.deleteZeroPrefix(requestVO.getOutAllocateOrderLineId());
            List<AllocateOrderDetailVO> allocateOrderDetailVOS = existOrderMap.get(outAllocateOrderId + "-" + outLineId);
            if (CollectionUtils.isEmpty(allocateOrderDetailVOS)) {
                buildErrorDetail(recordId, requestVO, null, "OTS没有此订单存在!");
                continue;
            }
            AllocateOrderDetailVO allocateOrderDetailVO = allocateOrderDetailVOS.get(0);
            Boolean shouldPersistence = doAllocateDiff(recordId, requestVO, allocateOrderDetailVO);
            if (shouldPersistence) {
                successCount++;
            }

        }


        return successCount;
    }

    private Boolean doAllocateDiff(Long recordId, Object requestVO, Object allocateOrderDetailVO) {
        try {
            List<OrderCompareErrorResult> results = compareTwoClass(requestVO, allocateOrderDetailVO);
            if (CollectionUtils.isEmpty(results)) {
                return true;
            }
            String errorMessage = packageErrorMessage(results);
            buildErrorDetail(recordId, requestVO, allocateOrderDetailVO, errorMessage);
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            buildErrorDetail(recordId, requestVO, allocateOrderDetailVO, "对账异常:" + e.getMessage());
            return false;
        }

    }

    private Integer doApplyAllocateOrderDiff(@NotNull List<ApplyAllocateCompareRequestVO> request, Long recordId) {

        //success count ,init zero success
        int successCount = 0;
        //collection to be compared code list
        List<String> sapCodeList = request.stream().map(ApplyAllocateCompareRequestVO::getOutAllocateApplyOrderId).filter(StringUtils::isNotBlank).distinct().collect(Collectors.toList());
        List<AllocateApplyOrderListDTO> applyAllocateOTSList = new ArrayList<>();
        int idListSize = sapCodeList.size();
        //因为ids入参元素过多，可能造成es查询条件太多而报错，对ID进行分片分批查询
        int idListPage = (idListSize % 1000) > 0 ? (idListSize / 1000 + 1) : idListSize / 1000;
        for (int i = 0; i < idListPage; i++) {
            List<String> pageSapCodeList = (i == idListPage - 1) ? sapCodeList.subList(i * 1000, sapCodeList.size()) : sapCodeList.subList(i * 1000, (i + 1) * 1000);


            AllocateApplyOrderQueryRequest allocateApplyOrderQueryRequest = new AllocateApplyOrderQueryRequest();
            allocateApplyOrderQueryRequest.setOutAllocateApplyOrderIds(pageSapCodeList);
            allocateApplyOrderQueryRequest.setStart(0);
            allocateApplyOrderQueryRequest.setLimit(querySize);

            Result<List<AllocateApplyOrderListDTO>> searchRepones = esAllocateApplyOrderIndexRepository.queryEsAllocateApplyOrderIndexList(allocateApplyOrderQueryRequest);
            if (Objects.isNull(searchRepones) || CollectionUtils.isEmpty(searchRepones.getResult())) {
                continue;
            }
            //pull all order list
            applyAllocateOTSList.addAll(searchRepones.getResult());
            int total = searchRepones.getTotal();
            if (total > querySize) {
                int page = ((total % querySize) > 0) ? ((total / querySize) + 1) : (total / querySize);
                for (int j = 1; j < page; j++) {
                    allocateApplyOrderQueryRequest.setStart(j * querySize);
                    List<AllocateApplyOrderListDTO> pageResult = esAllocateApplyOrderIndexRepository.queryEsAllocateApplyOrderIndexList(allocateApplyOrderQueryRequest).getResult();
                    applyAllocateOTSList.addAll(pageResult);
                }
            }
        }
        if (CollectionUtils.isEmpty(applyAllocateOTSList)) {
            request.forEach(requestVO -> buildErrorDetail(recordId, requestVO, null, "OTS没有此订单存在!")
            );
            return 0;
        }
        //db exist allocate order ,group by sap out code and line id,ots persistence outLineId include special prefix ,only sub intercept real line id
        Map<String, List<AllocateApplyOrderListDTO>> existOrderMap = applyAllocateOTSList.stream().collect(Collectors.groupingBy(o -> o.getOutAllocateApplyOrderId() + "-"
                + InfoUtil.deleteZeroPrefix(StringUtils.isNotBlank(o.getOutLineNo()) ? (o.getOutLineNo().split("_")[o.getOutLineNo().split("_").length - 1]) : "")));


        for (ApplyAllocateCompareRequestVO requestVO : request) {
            String outAllocateOrderId = requestVO.getOutAllocateApplyOrderId();
            //delete prefix zero
            String outLineId = InfoUtil.deleteZeroPrefix(requestVO.getOutLineNo());

            List<AllocateApplyOrderListDTO> allocateApplyOrderListDTOs = existOrderMap.get(outAllocateOrderId + "-" + outLineId);

            if (CollectionUtils.isEmpty(allocateApplyOrderListDTOs)) {
                buildErrorDetail(recordId, requestVO, null, "OTS没有此订单存在!");
                continue;
            }
            AllocateApplyOrderListDTO allocateApplyOrderListDTO = allocateApplyOrderListDTOs.get(0);
            Boolean shouldPersistence = doApplyDiff(recordId, requestVO, allocateApplyOrderListDTO);
            if (shouldPersistence) {
                successCount++;
            }

        }
        return successCount;
    }

    private Boolean doApplyDiff(Long recordId, ApplyAllocateCompareRequestVO source, AllocateApplyOrderListDTO target) {

        StringBuilder stringBuilder = new StringBuilder();
        if (!Objects.equals(String.valueOf(source.getCustomer()), String.valueOf(target.getCustomerAddressCode()))) {
            List<OrderCompareErrorResult> errorResult = Lists.newArrayList(new OrderCompareErrorResult() {{
                setSource(source.getCustomer());
                setTarget(target.getCustomerAddressCode());
                setText("客户地址编码");
            }});
            stringBuilder.append(packageErrorMessage(errorResult));
        }

        if (!Objects.equals(String.valueOf(source.getFactoryCode()), String.valueOf(target.getFactoryCode()))) {
            List<OrderCompareErrorResult> errorResult = Lists.newArrayList(new OrderCompareErrorResult() {{
                setSource(source.getFactoryCode());
                setTarget(target.getFactoryCode());
                setText("工厂编码");
            }});
            stringBuilder.append(packageErrorMessage(errorResult));
        }

        if (!Objects.equals(String.valueOf(source.getInventoryCode()), String.valueOf(target.getInventoryCode()))) {
            List<OrderCompareErrorResult> errorResult = Lists.newArrayList(new OrderCompareErrorResult() {{
                setSource(source.getInventoryCode());
                setTarget(target.getInventoryCode());
                setText("库存地点编码");
            }});
            stringBuilder.append(packageErrorMessage(errorResult));
        }

        if (!Objects.equals(String.valueOf(source.getHopeDeliveryTime()), String.valueOf(target.getHopeDeliveryTime()))) {
            List<OrderCompareErrorResult> errorResult = Lists.newArrayList(new OrderCompareErrorResult() {{
                setSource(source.getHopeDeliveryTime());
                setTarget(target.getHopeDeliveryTime());
                setText("期望交货日期");
            }});
            stringBuilder.append(packageErrorMessage(errorResult));
        }


        SimpleDateFormat formatDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = null != target.getGmtCreate() ? formatDateFormat.format(target.getGmtCreate()) : "null";
        if (!Objects.equals(String.valueOf(source.getGmtCreate()), format)) {
            List<OrderCompareErrorResult> errorResult = Lists.newArrayList(new OrderCompareErrorResult() {{
                setSource(source.getGmtCreate());
                setTarget(format);
                setText("创建时间");
            }});
            stringBuilder.append(packageErrorMessage(errorResult));
        }

        if (!Objects.equals(String.valueOf(source.getScItemId()), String.valueOf(target.getScItemId()))) {
            List<OrderCompareErrorResult> errorResult = Lists.newArrayList(new OrderCompareErrorResult() {{
                setSource(source.getScItemId());
                setTarget(target.getScItemId());
                setText("货品编码");
            }});
            stringBuilder.append(packageErrorMessage(errorResult));
        }

        if (!Objects.equals(String.valueOf(source.getApplyQuantity()), String.valueOf(target.getApplyQuantity()))) {
            List<OrderCompareErrorResult> errorResult = Lists.newArrayList(new OrderCompareErrorResult() {{
                setSource(source.getApplyQuantity());
                setTarget(String.valueOf(target.getApplyQuantity()));
                setText("预报量");
            }});
            stringBuilder.append(packageErrorMessage(errorResult));
        }

        if (!Objects.equals(String.valueOf(source.getReplyQuantity()), String.valueOf(target.getReplyQuantity()))) {
            List<OrderCompareErrorResult> errorResult = Lists.newArrayList(new OrderCompareErrorResult() {{
                setSource(source.getReplyQuantity());
                setTarget(String.valueOf(target.getReplyQuantity()));
                setText("回复量");
            }});
            stringBuilder.append(packageErrorMessage(errorResult));
        }

        String sourceUNitPrice = StringUtils.isNotBlank(source.getUnitPrice()) ? String.valueOf(new BigDecimal(source.getUnitPrice()).setScale(2, RoundingMode.HALF_UP)) : "null";
        String targetUnitPrice = null != source.getUnitPrice() ? String.valueOf(target.getUnitPrice().setScale(2, RoundingMode.HALF_UP)) : "null";
        if (!Objects.equals(sourceUNitPrice, targetUnitPrice)) {
            List<OrderCompareErrorResult> errorResult = Lists.newArrayList(new OrderCompareErrorResult() {{
                setSource(sourceUNitPrice);
                setTarget(targetUnitPrice);
                setText("单价");
            }});
            stringBuilder.append(packageErrorMessage(errorResult));
        }

        if (StringUtils.isBlank(stringBuilder.toString())) {
            return true;
        }

        buildErrorDetail(recordId, source, target, stringBuilder.toString());

        return false;

    }

    private Integer doNykAllocateOrderDiff(@NotNull List<OrderCompareAllocateRequestVO> request, Long recordId) {

        //success count ,init zero success
        int successCount = 0;
        //collection to be compared code list
        List<String> sapCodeList = request.stream().map(OrderCompareAllocateRequestVO::getOutAllocateOrderId).filter(StringUtils::isNotBlank).distinct().collect(Collectors.toList());
        //distinguish is plan or sale allocate ,plan allocate should param use outAllocateOrderIds ,not nykIds
        boolean isNykPlanCompare = request.stream().anyMatch(o -> NYK_PLAN_FLAG.equals(o.getAllocateType()));
        List<AllocateOrderDetailVO> allocateOrderDetailVOList = new ArrayList<>();
        int idListSize = sapCodeList.size();
        //因为ids入参元素过多，可能造成es查询条件太多而报错，对ID进行分片分批查询
        int idListPage = (idListSize % 1000) > 0 ? (idListSize / 1000 + 1) : idListSize / 1000;
        for (int i = 0; i < idListPage; i++) {
            List<String> pageSapCodeList = (i == idListPage - 1) ? sapCodeList.subList(i * 1000, sapCodeList.size()) : sapCodeList.subList(i * 1000, (i + 1) * 1000);

            AllocateOrderDetailSearchRequest allocateOrderDetailSearchRequest = new AllocateOrderDetailSearchRequest();
            if (isNykPlanCompare) {
                allocateOrderDetailSearchRequest.setOutAllocateOrderIds(pageSapCodeList);
            } else {
                allocateOrderDetailSearchRequest.setNykIds(pageSapCodeList);
            }

            allocateOrderDetailSearchRequest.setStart(0);
            allocateOrderDetailSearchRequest.setLimit(querySize);
            Result<List<AllocateOrderDetailVO>> searchRepones = allocateOrderReadService.search(allocateOrderDetailSearchRequest);
            if (Objects.isNull(searchRepones) || CollectionUtils.isEmpty(searchRepones.getResult())) {
                continue;
            }
            //pull all order list
            allocateOrderDetailVOList.addAll(searchRepones.getResult());
            int total = searchRepones.getTotal();
            if (total > querySize) {
                int page = ((total % querySize) > 0) ? ((total / querySize) + 1) : (total / querySize);
                for (int j = 1; j < page; j++) {
                    allocateOrderDetailSearchRequest.setStart(j * querySize);
                    List<AllocateOrderDetailVO> pageResult = allocateOrderReadService.search(allocateOrderDetailSearchRequest).getResult();
                    allocateOrderDetailVOList.addAll(pageResult);
                }
            }
        }

        if (CollectionUtils.isEmpty(allocateOrderDetailVOList)) {
            request.forEach(requestVO -> buildErrorDetail(recordId, requestVO, null, "OTS没有此订单存在!")
            );
            return 0;
        }

        Map<String, List<AllocateOrderDetailVO>> existOrderMap = allocateOrderDetailVOList.stream().collect(Collectors.groupingBy(o -> o.getOutAllocateOrderId() + "-" +
                (StringUtils.isNotBlank(o.getOutAllocateOrderLineId()) ? InfoUtil.deleteZeroPrefix(o.getOutAllocateOrderLineId()) : "")));

        for (OrderCompareAllocateRequestVO requestVO : request) {
            String outAllocateOrderId = requestVO.getOutAllocateOrderId();
            //delete prefix zero
            String outLineId = InfoUtil.deleteZeroPrefix(requestVO.getOutAllocateOrderLineId());
            List<AllocateOrderDetailVO> allocateOrderDetailVOS = existOrderMap.get(outAllocateOrderId + "-" + outLineId);
            if (CollectionUtils.isEmpty(allocateOrderDetailVOS)) {
                buildErrorDetail(recordId, requestVO, null, "OTS没有此订单存在!");
                continue;
            }
            AllocateOrderDetailVO allocateOrderDetailVO = allocateOrderDetailVOS.get(0);
            Boolean shouldPersistence = doNykAllocateDiff(recordId, requestVO, allocateOrderDetailVO);
            if (shouldPersistence) {
                successCount++;
            }

        }

        return successCount;
    }

    private Boolean doNykAllocateDiff(Long recordId, OrderCompareAllocateRequestVO source, AllocateOrderDetailVO target) {
        StringBuilder stringBuilder = new StringBuilder();

        if (!Objects.equals(InfoUtil.deleteZeroPrefix(source.getScItemCode()), target.getScItemCode())) {
            List<OrderCompareErrorResult> errorResult = Lists.newArrayList(new OrderCompareErrorResult() {{
                setSource(InfoUtil.deleteZeroPrefix(source.getScItemCode()));
                setTarget(target.getScItemCode());
                setText("物料代码");
            }});
            stringBuilder.append(packageErrorMessage(errorResult));
        }

        if (!Objects.equals(source.getQuantity(), target.getQuantity())) {
            List<OrderCompareErrorResult> errorResult = Lists.newArrayList(new OrderCompareErrorResult() {{
                setSource(source.getQuantity());
                setTarget(target.getQuantity());
                setText("销售订单数量");
            }});
            stringBuilder.append(packageErrorMessage(errorResult));
        }

        if (!Objects.equals(source.getConfirmQuantity(), target.getConfirmQuantity())) {
            List<OrderCompareErrorResult> errorResult = Lists.newArrayList(new OrderCompareErrorResult() {{
                setSource(source.getConfirmQuantity());
                setTarget(target.getConfirmQuantity());
                setText("确认数量");
            }});
            stringBuilder.append(packageErrorMessage(errorResult));
        }

//        if (!Objects.equals(source.getShipFactoryCode(), target.getShipFactoryCode())) {
//            List<OrderCompareErrorResult> errorResult = Lists.newArrayList(new OrderCompareErrorResult() {{
//                setSource(source.getShipFactoryCode());
//                setTarget(target.getShipFactoryCode());
//                setText("发货工厂");
//            }});
//            stringBuilder.append(packageErrorMessage(errorResult));
//        }

        if (StringUtils.isBlank(stringBuilder.toString())) {
            return true;
        }

        buildErrorDetail(recordId, source, target, stringBuilder.toString());

        return false;
    }

    private void prepareAllocateData(@Nonnull List<OrderCompareAllocateRequestVO> request) {
        request.forEach(o -> {

                    String allocateType = o.getAllocateType();
                    //是否是计划调拨单 产品要求：SAP中销售调拨单报表中两个字段逻辑有问题，平台中需特判该类型的调拨单的两个字段不对比 到货数量、在途数量
                    boolean isPlanAllocate = "plan".equals(allocateType);
                    o.setScItemCode(InfoUtil.deleteZeroPrefix(o.getScItemCode()));
                    o.setAddressCode(InfoUtil.deleteZeroPrefix(o.getAddressCode()));

                    if (StringUtils.isNotBlank(o.getGiftQuantity())) {
                        if (BigDecimal.ZERO.compareTo(new BigDecimal(o.getGiftQuantity())) == 0) {
                            o.setGiftQuantity(null);
                        }else {
                            o.setGiftQuantity(String.valueOf(new BigDecimal(o.getGiftQuantity()).setScale(2,RoundingMode.HALF_UP)));
                        }
                    }

            if (StringUtils.isNotBlank(o.getQuantity())) {
                if (BigDecimal.ZERO.compareTo(new BigDecimal(o.getQuantity())) == 0) {
                    o.setQuantity(null);
                }else {
                    o.setQuantity(String.valueOf(new BigDecimal(o.getQuantity()).setScale(2,RoundingMode.HALF_UP)));
                }
            }

                    if (StringUtils.isNotBlank(o.getReceiveQuantity())) {
                        if (BigDecimal.ZERO.compareTo(new BigDecimal(o.getReceiveQuantity())) == 0) {
                            o.setReceiveQuantity(null);
                        }else {
                            o.setReceiveQuantity(String.valueOf(new BigDecimal(o.getReceiveQuantity()).setScale(2,RoundingMode.HALF_UP)));
                        }
                    }

                    if (StringUtils.isNotBlank(o.getConfirmQuantity())) {
                        if (BigDecimal.ZERO.compareTo(new BigDecimal(o.getConfirmQuantity())) == 0) {
                            o.setConfirmQuantity(null);
                        }else {
                            o.setConfirmQuantity(String.valueOf(new BigDecimal(o.getConfirmQuantity()).setScale(2,RoundingMode.HALF_UP)));
                        }
                    }

                    if (StringUtils.isNotBlank(o.getShipQuantity())) {
                        if (BigDecimal.ZERO.compareTo(new BigDecimal(o.getShipQuantity())) == 0) {
                            o.setShipQuantity(null);
                        }else {
                            o.setShipQuantity(String.valueOf(new BigDecimal(o.getShipQuantity()).setScale(2,RoundingMode.HALF_UP)));
                        }
                    }

                    if (StringUtils.isNotBlank(o.getDeliveryQuantity())) {
                        if (BigDecimal.ZERO.compareTo(new BigDecimal(o.getDeliveryQuantity())) == 0) {
                            o.setDeliveryQuantity(null);
                        }else {
                            o.setDeliveryQuantity(String.valueOf(new BigDecimal(o.getDeliveryQuantity()).setScale(3,RoundingMode.HALF_UP)));
                        }
                    }

                    if (StringUtils.isNotBlank(o.getNotIssuedQuantity())) {
                        if (BigDecimal.ZERO.compareTo(new BigDecimal(o.getNotIssuedQuantity())) == 0) {
                            o.setNotIssuedQuantity(null);
                        }
                    }

                    if (StringUtils.isNotBlank(o.getTransQuantity())) {
                        if (BigDecimal.ZERO.compareTo(new BigDecimal(o.getTransQuantity())) == 0) {
                            o.setTransQuantity(null);
                        } else {
                            o.setTransQuantity(String.valueOf(new BigDecimal(o.getTransQuantity()).setScale(2, RoundingMode.HALF_UP)));
                        }
                    }

                    if (StringUtils.isNotBlank(o.getPrice())) {
                        if (BigDecimal.ZERO.compareTo(new BigDecimal(o.getPrice())) == 0) {
                            o.setPrice(null);
                        } else {
                            o.setPrice(String.valueOf(new BigDecimal(o.getPrice()).setScale(2, RoundingMode.HALF_UP)));
                        }
                    } else {
                        o.setPrice(null);
                    }

                    if (StringUtils.isNotBlank(o.getAmount())) {
                        if (BigDecimal.ZERO.compareTo(new BigDecimal(o.getAmount())) == 0) {
                            o.setAmount(null);
                        } else {
                            o.setAmount(String.valueOf(new BigDecimal(o.getAmount()).setScale(2, RoundingMode.HALF_UP)));
                        }
                    } else {
                        o.setAmount(null);
                    }


                    if (StringUtils.isNotBlank(o.getDeliveryAmt())) {
                        if (BigDecimal.ZERO.compareTo(new BigDecimal(o.getDeliveryAmt())) == 0) {
                            o.setDeliveryAmt(null);
                        } else {
                            o.setDeliveryAmt(String.valueOf(new BigDecimal(o.getDeliveryAmt()).setScale(2, RoundingMode.HALF_UP)));
                        }
                    } else {
                        o.setDeliveryAmt(null);
                    }

                    if (StringUtils.isNotBlank(o.getDeliveryDiscountAmt())) {
                        if (BigDecimal.ZERO.compareTo(new BigDecimal(o.getDeliveryDiscountAmt())) == 0) {
                            o.setDeliveryDiscountAmt(null);
                        } else {
                            o.setDeliveryDiscountAmt(String.valueOf(new BigDecimal(o.getDeliveryDiscountAmt()).setScale(2, RoundingMode.HALF_UP)));
                        }
                    } else {
                        o.setDeliveryDiscountAmt(null);
                    }

                    if (StringUtils.isNotBlank(o.getShippedAmt())) {
                        if (BigDecimal.ZERO.compareTo(new BigDecimal(o.getShippedAmt())) == 0) {
                            o.setShippedAmt(null);
                        } else {
                            o.setShippedAmt(String.valueOf(new BigDecimal(o.getShippedAmt()).setScale(2, RoundingMode.HALF_UP)));
                        }
                    } else {
                        o.setShippedAmt(null);
                    }

                    if (StringUtils.isNotBlank(o.getShippedDiscountAmt())) {
                        if (BigDecimal.ZERO.compareTo(new BigDecimal(o.getShippedDiscountAmt())) == 0) {
                            o.setShippedDiscountAmt(null);
                        } else {
                            o.setShippedDiscountAmt(String.valueOf(new BigDecimal(o.getShippedDiscountAmt()).setScale(2, RoundingMode.HALF_UP)));
                        }
                    } else {
                        o.setShippedDiscountAmt(null);
                    }
                    //计划和销售排除部分字段
                    if (isPlanAllocate) {
                        o.setShipFactoryCode(null);
                        o.setDocDate(null);
                        o.setDeliveryAmt(null);
                        o.setDeliveryDiscountAmt(null);
                        o.setPrice(null);
                        o.setAmount(null);
                        o.setShippedAmt(null);
                        o.setShippedDiscountAmt(null);
                        o.setAddressCode(null);
                    } else {
                        o.setShipFactoryCode(null);
                        o.setReceiveQuantity(null);
                        o.setTransQuantity(null);
                    }

                    // 产品要求：
                    // 【销售调拨对账】识别单号为63开头的（去前导0）销售调拨单,判定为退单，销售订单数量、未走量、折前总金额、交货单数量、交货单折前金额、
                    // 交货单折后金额、出库数量、出库日期、到货数量、在途量、出库折前金额、出库折后金额字段不对比，直接返回正确
                    String outAllocateOrderId = InfoUtil.deleteZeroPrefix(o.getOutAllocateOrderId());
                    boolean specExcludeFlagForSaleAllocate = (!isPlanAllocate) &&
                            (StringUtils.isNotBlank(outAllocateOrderId) && outAllocateOrderId.startsWith("63"));
                    //产品要起：
                    //导入内容中，退货数量为负值，判定为退单，需屏蔽部分字段的对比 TRUE=退单
                    boolean chargebackQuantityFlag = StringUtils.isNotBlank(o.getChargebackQuantity()) ?
                            BigDecimal.ZERO.compareTo(new BigDecimal(o.getChargebackQuantity())) > 0 :
                            Boolean.FALSE;


                    //销售调拨退单不进行下列字段对比
                    if (specExcludeFlagForSaleAllocate) {
                        o.setQuantity(null);
                        o.setConfirmQuantity(null);
                        o.setNotIssuedQuantity(null);
                        o.setConfirmDate(null);
                        o.setGiftQuantity(null);
                        o.setAmount(null);
                        o.setDeliveryQuantity(null);
                        o.setDeliveryAmt(null);
                        o.setDeliveryDiscountAmt(null);
                        o.setShipQuantity(null);
                        o.setShipTime(null);
                        o.setShippedAmt(null);
                        o.setShippedDiscountAmt(null);
                    }
                    //计划调拨单退单不进行下列字段对比
                    if (chargebackQuantityFlag) {
                        o.setConfirmQuantity(null);
                        o.setNotIssuedQuantity(null);
                        o.setConfirmDate(null);
                        o.setGiftQuantity(null);
                        o.setReceiveQuantity(null);
                        o.setTransQuantity(null);
                    }
                    //产品要求：
                    //存在拒绝原因销售调拨单对账需要排除部分字段
                    if ((!isPlanAllocate && !specExcludeFlagForSaleAllocate) && StringUtils.isNotBlank(o.getRefuseReason())) {
                        o.setQuantity(null);
                        o.setNotIssuedQuantity(null);
                        o.setAmount(null);
                    }

                }

        );
    }

    private void preparaSaleData(@NotNull List<SalesOrderCompareRequestVO> request) {
        for (SalesOrderCompareRequestVO requestVO : request) {
            boolean needNegative = false;
            String orderType = requestVO.getOrderType();
            if (StringUtils.isNotBlank(orderType) && Objects.nonNull(SaleOrderTag.of(orderType))) {

                requestVO.setOrderType(SaleOrderTag.of(orderType).getDesc());
                if (requestVO.getOrderType().contains(returnKeywordText)) {
                    needNegative = true;
                }
            }

            if (needNegative) {
                if (StringUtils.isNotBlank(requestVO.getOrderQuantity())) {
                    requestVO.setOrderQuantity(requestVO.getOrderQuantity().replace("-", ""));
                }

            }

            String nkPrice = requestVO.getNkPrice();
            if (StringUtils.isNotBlank(nkPrice)) {
                if (BigDecimal.ZERO.compareTo(new BigDecimal(nkPrice)) == 0) {
                    requestVO.setNkPrice(null);
                } else {
                    requestVO.setNkPrice(String.valueOf(new BigDecimal(nkPrice).setScale(2, RoundingMode.HALF_UP)));
                }
            }

            String orderQuantity = requestVO.getOrderQuantity();
            if (StringUtils.isNotBlank(orderQuantity)) {
                if (BigDecimal.ZERO.compareTo(new BigDecimal(orderQuantity)) == 0) {
                    requestVO.setOrderQuantity(null);
                } else {
                    requestVO.setOrderQuantity(String.valueOf(new BigDecimal(orderQuantity).setScale(2, RoundingMode.HALF_UP)));
                }
            }

            String discount = requestVO.getDiscount();
            if (StringUtils.isNotBlank(discount)) {
                if (BigDecimal.ZERO.compareTo(new BigDecimal(discount)) == 0) {
                    requestVO.setDiscount(null);
                } else {
                    requestVO.setDiscount(String.valueOf(new BigDecimal(discount).setScale(2, RoundingMode.HALF_UP)));
                }
            }

            String dctBeforePrice = requestVO.getDctBeforePrice();
            if (StringUtils.isNotBlank(dctBeforePrice)) {
                if (BigDecimal.ZERO.compareTo(new BigDecimal(dctBeforePrice)) == 0) {
                    requestVO.setDctBeforePrice(null);
                } else {
                    requestVO.setDctBeforePrice(String.valueOf(new BigDecimal(dctBeforePrice).setScale(4, RoundingMode.HALF_UP)).replace("-", ""));
                }
            }

            String orderRegularPrice = requestVO.getOrderRegularPrice();
            if (StringUtils.isNotBlank(orderRegularPrice)) {
                if (BigDecimal.ZERO.compareTo(new BigDecimal(orderRegularPrice)) == 0) {
                    requestVO.setOrderRegularPrice(null);
                } else {
                    requestVO.setOrderRegularPrice(String.valueOf(new BigDecimal(orderRegularPrice).setScale(4, RoundingMode.HALF_UP)).replace("-", ""));
                }

            }

            String deliveryQuantityAndBaseUnit = requestVO.getDeliveryQuantityAndBaseUnit();
            if (StringUtils.isNotBlank(deliveryQuantityAndBaseUnit)) {
                if (BigDecimal.ZERO.compareTo(new BigDecimal(deliveryQuantityAndBaseUnit)) == 0) {
                    requestVO.setDeliveryQuantityAndBaseUnit(null);
                } else {
                    requestVO.setDeliveryQuantityAndBaseUnit(String.valueOf(new BigDecimal(deliveryQuantityAndBaseUnit).setScale(3, RoundingMode.HALF_UP)).replace("-", ""));
                }
            }

            String receiptQuantity = requestVO.getReceiptQuantity();
            if (StringUtils.isNotBlank(receiptQuantity)) {
                if (BigDecimal.ZERO.compareTo(new BigDecimal(receiptQuantity)) == 0) {
                    requestVO.setReceiptQuantity(null);
                } else {
                    requestVO.setReceiptQuantity(String.valueOf(new BigDecimal(receiptQuantity).setScale(3, RoundingMode.HALF_UP)).replace("-", ""));
                }
            }

            String beforeDiscountedAmount = requestVO.getBeforeDiscountedAmount();
            if (Objects.nonNull(beforeDiscountedAmount)) {
                if (BigDecimal.ZERO.compareTo(new BigDecimal(beforeDiscountedAmount)) == 0) {
                    requestVO.setBeforeDiscountedAmount(null);
                } else {
                    requestVO.setBeforeDiscountedAmount(String.valueOf(new BigDecimal(beforeDiscountedAmount).multiply(new BigDecimal(100)).setScale(0, RoundingMode.HALF_UP)).replace("-", ""));
                }
            }

            String regularPriceWithRebate = requestVO.getRegularPriceWithRebate();
            if (Objects.nonNull(regularPriceWithRebate)) {
                if (BigDecimal.ZERO.compareTo(new BigDecimal(regularPriceWithRebate)) == 0) {
                    requestVO.setRegularPriceWithRebate(null);
                } else {
                    requestVO.setRegularPriceWithRebate(String.valueOf(new BigDecimal(regularPriceWithRebate).multiply(new BigDecimal(100)).setScale(0, RoundingMode.HALF_UP)));
                }
            }

            String activityPrice = requestVO.getActivityPrice();
            if (Objects.nonNull(activityPrice)) {
                if (BigDecimal.ZERO.compareTo(new BigDecimal(activityPrice)) == 0) {
                    requestVO.setActivityPrice(null);
                } else {
                    requestVO.setActivityPrice(String.valueOf(new BigDecimal(activityPrice).multiply(new BigDecimal(100)).setScale(0, RoundingMode.HALF_UP)));
                }
            }

            String afterDiscountAmount = requestVO.getAfterDiscountAmount();
            if (Objects.nonNull(afterDiscountAmount)) {
                if (BigDecimal.ZERO.compareTo(new BigDecimal(afterDiscountAmount)) == 0) {
                    requestVO.setAfterDiscountAmount(null);
                } else {
                    requestVO.setAfterDiscountAmount(String.valueOf(new BigDecimal(afterDiscountAmount).multiply(new BigDecimal(100)).setScale(0, RoundingMode.HALF_UP).abs()));
                }
            }

            String deliveryNoteLineItemNo = requestVO.getDeliveryNoteLineItemNo();
            if (StringUtils.isNotBlank(deliveryNoteLineItemNo) && BigDecimal.ZERO.compareTo(new BigDecimal(deliveryNoteLineItemNo)) == 0) {
                requestVO.setDeliveryNoteLineItemNo(null);
            }
            String afterPodQuality = requestVO.getAfterPodQuality();
            if (StringUtils.isNotBlank(afterPodQuality)) {
                if (BigDecimal.ZERO.compareTo(new BigDecimal(afterPodQuality)) == 0) {
                    requestVO.setAfterPodQuality(null);
                } else {
                    requestVO.setAfterPodQuality(String.valueOf(new BigDecimal(afterPodQuality).setScale(3, RoundingMode.HALF_UP)));
                }
            }

            String beforeDiscountedAmountOfDeliveryNote = requestVO.getBeforeDiscountedAmountOfDeliveryNote();
            if (Objects.nonNull(beforeDiscountedAmountOfDeliveryNote)) {
                if (BigDecimal.ZERO.compareTo(new BigDecimal(beforeDiscountedAmountOfDeliveryNote)) == 0) {
                    requestVO.setBeforeDiscountedAmountOfDeliveryNote(null);
                } else {
                    requestVO.setBeforeDiscountedAmountOfDeliveryNote(String.valueOf(new BigDecimal(beforeDiscountedAmountOfDeliveryNote).multiply(new BigDecimal(100)).setScale(0, RoundingMode.HALF_UP)).replace("-", ""));
                }
            }

            String afterDiscountAmountOfDeliveryNote = requestVO.getAfterDiscountAmountOfDeliveryNote();
            if (Objects.nonNull(afterDiscountAmountOfDeliveryNote)) {
                if (BigDecimal.ZERO.compareTo(new BigDecimal(afterDiscountAmountOfDeliveryNote)) == 0) {
                    requestVO.setAfterDiscountAmountOfDeliveryNote(null);
                } else {
                    requestVO.setAfterDiscountAmountOfDeliveryNote(String.valueOf(new BigDecimal(afterDiscountAmountOfDeliveryNote).multiply(new BigDecimal(100)).setScale(0, RoundingMode.HALF_UP).abs()));
                }
            }

            String receiptLineItemNo = requestVO.getReceiptLineItemNo();
            if (StringUtils.isNotBlank(receiptLineItemNo) && BigDecimal.ZERO.compareTo(new BigDecimal(receiptLineItemNo)) == 0) {
                requestVO.setReceiptLineItemNo(null);
            }


            String receiptAmount = requestVO.getReceiptAmount();
            if (Objects.nonNull(receiptAmount)) {
                if (BigDecimal.ZERO.compareTo(new BigDecimal(receiptAmount)) == 0) {
                    requestVO.setReceiptAmount(null);
                } else {
                    requestVO.setReceiptAmount(String.valueOf(new BigDecimal(receiptAmount).multiply(new BigDecimal(100)).setScale(0, RoundingMode.HALF_UP).abs()));
                }
            }

            String receiptPrice = requestVO.getReceiptPrice();
            if (Objects.nonNull(receiptPrice)) {
                if (BigDecimal.ZERO.compareTo(new BigDecimal(receiptPrice)) == 0) {
                    requestVO.setReceiptPrice(null);
                } else {
                    requestVO.setReceiptPrice(String.valueOf(new BigDecimal(receiptPrice).multiply(new BigDecimal(10000)).setScale(0, RoundingMode.HALF_UP)));
                }

            }

            String deliveryOrdersQuality = requestVO.getDeliveryOrdersQuality();
            if (StringUtils.isNotBlank(deliveryOrdersQuality)) {
                if (BigDecimal.ZERO.compareTo(new BigDecimal(deliveryOrdersQuality)) == 0) {
                    requestVO.setDeliveryOrdersQuality(null);
                } else {
                    requestVO.setDeliveryOrdersQuality(String.valueOf(new BigDecimal(deliveryOrdersQuality).setScale(3, RoundingMode.HALF_UP)).replace("-", ""));
                }

            }

            String discountedPrice = requestVO.getDiscountedPrice();
            if (Objects.nonNull(discountedPrice)) {
                if (BigDecimal.ZERO.compareTo(new BigDecimal(discountedPrice)) == 0) {
                    requestVO.setDiscountedPrice(null);
                } else {
                    requestVO.setDiscountedPrice(String.valueOf(new BigDecimal(discountedPrice).setScale(4, RoundingMode.HALF_UP)));
                }
            }

            String regularAmountWithRebate = requestVO.getRegularAmountWithRebate();
            if (Objects.nonNull(regularAmountWithRebate)) {
                if (BigDecimal.ZERO.compareTo(new BigDecimal(regularAmountWithRebate)) == 0) {
                    requestVO.setRegularAmountWithRebate(null);
                } else {
                    requestVO.setRegularAmountWithRebate(String.valueOf(new BigDecimal(regularAmountWithRebate).multiply(new BigDecimal(100)).setScale(0, RoundingMode.HALF_UP).abs()));
                }

            }

        }
    }

    private void reductionImportObject(SalesOrderCompareRequestVO requestVO) {
        //as follows，need divide 100 for this amount
        // beforeDiscountedAmount
        //regularPriceWithRebate
        //activityPrice
        //afterDiscountAmount
        //beforeDiscountedAmountOfDeliveryNote
        //afterDiscountAmountOfDeliveryNote
        //receiptAmount
        //receiptPrice
        //regularAmountWithRebate
        String orderType = requestVO.getOrderType();
        boolean needNegativeAmount = Boolean.FALSE;
        if (StringUtils.isNotBlank(orderType) && orderType.contains(returnKeywordText)) {
            needNegativeAmount = Boolean.TRUE;
        }


        if (Objects.nonNull(requestVO.getBeforeDiscountedAmount())) {
            requestVO.setBeforeDiscountedAmount(String.valueOf(new BigDecimal(requestVO.getBeforeDiscountedAmount()).divide(new BigDecimal(100), 4, RoundingMode.HALF_UP)));
        }

        if (Objects.nonNull(requestVO.getRegularPriceWithRebate())) {
            requestVO.setRegularPriceWithRebate(String.valueOf(new BigDecimal(requestVO.getRegularPriceWithRebate()).divide(new BigDecimal(100), 4, RoundingMode.HALF_UP)));
        }

        if (Objects.nonNull(requestVO.getActivityPrice())) {
            requestVO.setActivityPrice(String.valueOf(new BigDecimal(requestVO.getActivityPrice()).divide(new BigDecimal(100), 4, RoundingMode.HALF_UP)));
        }

        if (Objects.nonNull(requestVO.getAfterDiscountAmount())) {
            requestVO.setAfterDiscountAmount(String.valueOf(new BigDecimal(requestVO.getAfterDiscountAmount()).divide(new BigDecimal(100), 4, RoundingMode.HALF_UP)));
            if (needNegativeAmount) {
                requestVO.setAfterDiscountAmount("-" + requestVO.getAfterDiscountAmount());
            }
        }

        if (Objects.nonNull(requestVO.getBeforeDiscountedAmountOfDeliveryNote())) {
            requestVO.setBeforeDiscountedAmountOfDeliveryNote(String.valueOf(new BigDecimal(requestVO.getBeforeDiscountedAmountOfDeliveryNote()).divide(new BigDecimal(100), 4, RoundingMode.HALF_UP)));
        }

        if (Objects.nonNull(requestVO.getAfterDiscountAmountOfDeliveryNote())) {
            requestVO.setAfterDiscountAmountOfDeliveryNote(String.valueOf(new BigDecimal(requestVO.getAfterDiscountAmountOfDeliveryNote()).divide(new BigDecimal(100), 4, RoundingMode.HALF_UP)));
            if (needNegativeAmount) {
                requestVO.setAfterDiscountAmountOfDeliveryNote("-" + requestVO.getAfterDiscountAmountOfDeliveryNote());
            }
        }

        if (Objects.nonNull(requestVO.getReceiptAmount())) {
            requestVO.setReceiptAmount(String.valueOf(new BigDecimal(requestVO.getReceiptAmount()).divide(new BigDecimal(100), 4, RoundingMode.HALF_UP)));
            if (needNegativeAmount) {
                requestVO.setReceiptAmount("-" + requestVO.getReceiptAmount());
            }
        }

        if (Objects.nonNull(requestVO.getReceiptPrice())) {
            requestVO.setReceiptPrice(String.valueOf(new BigDecimal(requestVO.getReceiptPrice()).divide(new BigDecimal(10000), 4, RoundingMode.HALF_UP)));
        }

        if (Objects.nonNull(requestVO.getRegularAmountWithRebate())) {
            requestVO.setRegularAmountWithRebate(String.valueOf(new BigDecimal(requestVO.getRegularAmountWithRebate()).divide(new BigDecimal(100), 4, RoundingMode.HALF_UP)));
            if (needNegativeAmount) {
                requestVO.setRegularAmountWithRebate("-" + requestVO.getRegularAmountWithRebate());
            }
        }


        //as follows,negative number need append
        // afterDiscountAmount
        //afterDiscountAmountOfDeliveryNote
        //receiptAmount
        //regularAmountWithRebate
        //getOrderQuantity
        //orderRegularPrice
        //deliveryQuantityAndBaseUnit
        //receiptQuantity
        //deliveryOrdersQuality
        if (StringUtils.isNotBlank(requestVO.getOrderQuantity()) && needNegativeAmount) {
            requestVO.setOrderQuantity("-" + requestVO.getOrderQuantity());
        }

        if (StringUtils.isNotBlank(requestVO.getOrderRegularPrice()) && needNegativeAmount) {
            requestVO.setOrderRegularPrice("-" + requestVO.getOrderRegularPrice());
        }

        if (StringUtils.isNotBlank(requestVO.getDeliveryQuantityAndBaseUnit()) && needNegativeAmount) {
            requestVO.setDeliveryQuantityAndBaseUnit("-" + requestVO.getDeliveryQuantityAndBaseUnit());
        }

        if (StringUtils.isNotBlank(requestVO.getReceiptQuantity()) && needNegativeAmount) {
            requestVO.setReceiptQuantity("-" + requestVO.getReceiptQuantity());
        }

        if (StringUtils.isNotBlank(requestVO.getDeliveryOrdersQuality()) && needNegativeAmount) {
            requestVO.setDeliveryOrdersQuality("-" + requestVO.getDeliveryOrdersQuality());
        }

        if (StringUtils.isNotBlank(requestVO.getDctBeforePrice()) && needNegativeAmount) {
            requestVO.setDctBeforePrice("-" + requestVO.getDctBeforePrice());
        }

        if (StringUtils.isNotBlank(requestVO.getBeforeDiscountedAmount()) && needNegativeAmount) {
            requestVO.setBeforeDiscountedAmount("-" + requestVO.getBeforeDiscountedAmount());
        }

        if (StringUtils.isNotBlank(requestVO.getBeforeDiscountedAmountOfDeliveryNote()) && needNegativeAmount) {
            requestVO.setBeforeDiscountedAmountOfDeliveryNote("-" + requestVO.getBeforeDiscountedAmountOfDeliveryNote());
        }


    }

    private void processAllocateResult(@NotNull List<AllocateOrderDetailVO> allocateOrderDetailVOList) {
        allocateOrderDetailVOList.forEach(o -> {
            //doc date format
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd");
            try {
                if (Objects.nonNull(o.getDocDate())) {
                    o.setDocDate(targetFormat.parse(format.format(o.getDocDate())));
                }
                if (Objects.nonNull(o.getConfirmDate())) {
                    o.setConfirmDate(targetFormat.parse(format.format(o.getConfirmDate())));
                }
                if (Objects.nonNull(o.getShipTime())) {
                    o.setShipTime(targetFormat.parse(format.format(o.getShipTime())));
                }
            } catch (ParseException e) {
                e.printStackTrace();
                return;
            }


            String giftQuantity = o.getGiftQuantity();
            if (StringUtils.isNotBlank(giftQuantity)) {
                if (BigDecimal.ZERO.compareTo(new BigDecimal(giftQuantity)) == 0) {
                    o.setGiftQuantity(null);
                }else {
                    o.setGiftQuantity(String.valueOf(new BigDecimal(o.getGiftQuantity()).setScale(2,RoundingMode.HALF_UP)));
                }
            }

            String quantity = o.getQuantity();
            if (StringUtils.isNotBlank(quantity)) {
                if (BigDecimal.ZERO.compareTo(new BigDecimal(quantity)) == 0) {
                    o.setQuantity(null);
                }else {
                    o.setQuantity(String.valueOf(new BigDecimal(quantity).setScale(2,RoundingMode.HALF_UP)));
                }
            }

            String confirmQuantity = o.getConfirmQuantity();
            if (StringUtils.isNotBlank(confirmQuantity)) {
                if (BigDecimal.ZERO.compareTo(new BigDecimal(confirmQuantity)) == 0) {
                    o.setConfirmQuantity(null);
                }else {
                    o.setConfirmQuantity(String.valueOf(new BigDecimal(confirmQuantity).setScale(2,RoundingMode.HALF_UP)));
                }
            }

            String shipQuantity = o.getShipQuantity();
            if (StringUtils.isNotBlank(shipQuantity)) {
                if (BigDecimal.ZERO.compareTo(new BigDecimal(shipQuantity)) == 0) {
                    o.setShipQuantity(null);
                }else {
                    o.setShipQuantity(String.valueOf(new BigDecimal(shipQuantity).setScale(2,RoundingMode.HALF_UP)));
                }
            }

            String receiveQuantity = o.getReceiveQuantity();
            if (StringUtils.isNotBlank(receiveQuantity)) {
                if (BigDecimal.ZERO.compareTo(new BigDecimal(receiveQuantity)) == 0) {
                    o.setReceiveQuantity(null);
                }else {
                    o.setReceiveQuantity(String.valueOf(new BigDecimal(receiveQuantity).setScale(2,RoundingMode.HALF_UP)));
                }
            }

            String transQuantity = o.getTransQuantity();
            if (StringUtils.isNotBlank(transQuantity)) {
                if (BigDecimal.ZERO.compareTo(new BigDecimal(transQuantity)) == 0) {
                    o.setTransQuantity(null);
                } else {
                    o.setTransQuantity(String.valueOf(new BigDecimal(transQuantity).setScale(2, RoundingMode.HALF_UP)));
                }
            }

            String deliveryQuantity = o.getDeliveryQuantity();
            if (StringUtils.isNotBlank(deliveryQuantity)) {
                if (BigDecimal.ZERO.compareTo(new BigDecimal(deliveryQuantity)) == 0) {
                    o.setDeliveryQuantity(null);
                }else{
                    o.setDeliveryQuantity(String.valueOf(new BigDecimal(deliveryQuantity).setScale(3,RoundingMode.HALF_UP)));
                }
            }
            String notIssuedQuantity = o.getNotIssuedQuantity();
            if (StringUtils.isNotBlank(notIssuedQuantity)) {
                if (BigDecimal.ZERO.compareTo(new BigDecimal(notIssuedQuantity)) == 0) {
                    o.setNotIssuedQuantity(null);
                }
            }

            String price = o.getPrice();
            if (StringUtils.isNotBlank(price)) {
                if (BigDecimal.ZERO.compareTo(new BigDecimal(price)) == 0) {
                    o.setPrice(null);
                } else {
                    o.setPrice(String.valueOf(new BigDecimal(price).setScale(2, RoundingMode.HALF_UP)));
                }
            }
            Integer type = o.getType();
            if (null != type) {
                //计划调拨不比对如下字段，产品需求
                if (1 == type) {
                    o.setShipFactoryCode(null);
                    o.setDocDate(null);
                    o.setDeliveryAmt(null);
                    o.setDeliveryDiscountAmt(null);
                    o.setPrice(null);
                    o.setAmount(null);
                    o.setShippedAmt(null);
                    o.setShippedDiscountAmt(null);
                    o.setAddressCode(null);
                    if (o.getReturnOrder()) {
                        chargeBackPlanBuild(o);
                    }
                }
                //总部销售调拨不进行如下字段比对
                if (2 == type) {
                    o.setShipFactoryCode(null);
                    o.setReceiveQuantity(null);
                    o.setTransQuantity(null);

                    //退单 不比对如下字段
                    boolean specExcludeFlagForSaleAllocate = StringUtils.isNotBlank(o.getOutAllocateOrderId()) && InfoUtil.deleteZeroPrefix(o.getOutAllocateOrderId()).startsWith("63");

                    if (specExcludeFlagForSaleAllocate) {
                        chargeBackSaleBuild(o);
                    }else {
                        //正向销售调拨单 存在拒绝原因的 不进行下列字段对比
                        if (o.getClosed()){
                            o.setQuantity(null);
                            o.setNotIssuedQuantity(null);
                            o.setAmount(null);
                        }
                    }

                }
            }


        });
    }

    private void chargeBackSaleBuild(AllocateOrderDetailVO o) {
        o.setQuantity(null);
        o.setConfirmQuantity(null);
        o.setNotIssuedQuantity(null);
        o.setConfirmDate(null);
        o.setGiftQuantity(null);
        o.setAmount(null);
        o.setDeliveryQuantity(null);
        o.setDeliveryAmt(null);
        o.setDeliveryDiscountAmt(null);
        o.setShipQuantity(null);
        o.setShipTime(null);
        o.setShippedAmt(null);
        o.setShippedDiscountAmt(null);
    }

    private void chargeBackPlanBuild(AllocateOrderDetailVO o) {
        o.setConfirmQuantity(null);
        o.setNotIssuedQuantity(null);
        o.setConfirmDate(null);
        o.setGiftQuantity(null);
        o.setReceiveQuantity(null);
        o.setTransQuantity(null);
    }

    private void processSaleResult(List<OrderLinePageQueryResponse> allocateOrderDetailVOList) {
        allocateOrderDetailVOList.forEach(o -> {
            // date format
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            try {
                if (Objects.nonNull(o.getOrderGmtCreate())) {
                    o.setOrderGmtCreate(targetFormat.format(format.parse(o.getOrderGmtCreate())));
                }
                if (Objects.nonNull(o.getDeliveryDate())) {
                    o.setDeliveryDate(targetFormat.format(format.parse(o.getDeliveryDate())));
                }

                if (Objects.nonNull(o.getDeliveryNoteCreateDate())) {
                    o.setDeliveryNoteCreateDate(targetFormat.format(format.parse(o.getDeliveryNoteCreateDate())));
                }
                if (Objects.nonNull(o.getShipmentPostingDate())) {
                    o.setShipmentPostingDate(targetFormat.format(format.parse(o.getShipmentPostingDate())));
                }

                if (Objects.nonNull(o.getReceiptDate())) {
                    o.setReceiptDate(targetFormat.format(format.parse(o.getReceiptDate())));
                }
                if (Objects.nonNull(o.getReceiptCreateDate())) {
                    o.setReceiptCreateDate(targetFormat.format(format.parse(o.getReceiptCreateDate())));
                }
            } catch (ParseException e) {
                e.printStackTrace();
                return;
            }
            String nkPrice = o.getNkPrice();
            if (StringUtils.isNotBlank(nkPrice)) {
                if (BigDecimal.ZERO.compareTo(new BigDecimal(nkPrice)) == 0) {
                    o.setNkPrice(null);
                } else {
                    o.setNkPrice(String.valueOf(new BigDecimal(nkPrice).setScale(2, RoundingMode.HALF_UP)));
                }
            }

            String orderQuantity = o.getOrderQuantity();
            if (StringUtils.isNotBlank(orderQuantity)) {
                if (BigDecimal.ZERO.compareTo(new BigDecimal(orderQuantity)) == 0) {
                    o.setOrderQuantity(null);
                } else {
                    o.setOrderQuantity(String.valueOf(new BigDecimal(orderQuantity).setScale(2, RoundingMode.HALF_UP)));
                }
            }


            //amount format
            String discount = o.getDiscount();
            if (StringUtils.isNotBlank(discount)) {
                if (discount.contains("-")) {
                    //sample： 500.00-，应该把负号放在前面
                    discount = "-" + discount.replace("-", "");
                }

                if (BigDecimal.ZERO.compareTo(new BigDecimal(discount)) == 0) {
                    o.setDiscount(null);
                } else {
                    o.setDiscount(String.valueOf(new BigDecimal(discount).setScale(2, RoundingMode.HALF_UP)));
                }

            }

            String dctBeforePrice = o.getDctBeforePrice();
            if (StringUtils.isNotBlank(dctBeforePrice)) {
                if (BigDecimal.ZERO.compareTo(new BigDecimal(dctBeforePrice)) == 0) {
                    o.setDctBeforePrice(null);
                } else {
                    o.setDctBeforePrice(String.valueOf(new BigDecimal(dctBeforePrice).divide(new BigDecimal(100), 4, RoundingMode.HALF_UP)));
                }
            }

            String orderRegularPrice = o.getOrderRegularPrice();
            if (StringUtils.isNotBlank(orderRegularPrice)) {
                if (BigDecimal.ZERO.compareTo(new BigDecimal(orderRegularPrice)) == 0) {
                    o.setOrderRegularPrice(null);
                } else {
                    o.setOrderRegularPrice(String.valueOf(new BigDecimal(orderRegularPrice).divide(new BigDecimal(100), 4, RoundingMode.HALF_UP)));
                }
            }

            String deliveryQuantityAndBaseUnit = o.getDeliveryQuantityAndBaseUnit();
            if (StringUtils.isNotBlank(deliveryQuantityAndBaseUnit)) {
                if (BigDecimal.ZERO.compareTo(new BigDecimal(deliveryQuantityAndBaseUnit)) == 0) {
                    o.setDeliveryQuantityAndBaseUnit(null);
                } else {
                    o.setDeliveryQuantityAndBaseUnit(String.valueOf(new BigDecimal(deliveryQuantityAndBaseUnit).setScale(3, RoundingMode.HALF_UP)));
                }
            }

            String receiptQuantity = o.getReceiptQuantity();
            if (StringUtils.isNotBlank(receiptQuantity)) {
                if (BigDecimal.ZERO.compareTo(new BigDecimal(receiptQuantity)) == 0) {
                    o.setReceiptQuantity(null);
                } else {
                    o.setReceiptQuantity(String.valueOf(new BigDecimal(receiptQuantity).setScale(3, RoundingMode.HALF_UP)));
                }
            }

            Long beforeDiscountedAmount = o.getBeforeDiscountedAmount();
            if (Objects.nonNull(beforeDiscountedAmount) && BigDecimal.ZERO.compareTo(new BigDecimal(beforeDiscountedAmount)) == 0) {
                o.setBeforeDiscountedAmount(null);
            }

            Long regularPriceWithRebate = o.getRegularPriceWithRebate();
            if (Objects.nonNull(regularPriceWithRebate) && BigDecimal.ZERO.compareTo(new BigDecimal(regularPriceWithRebate)) == 0) {
                o.setRegularPriceWithRebate(null);
            }

            Long activityPrice = o.getActivityPrice();
            if (Objects.nonNull(activityPrice) && BigDecimal.ZERO.compareTo(new BigDecimal(activityPrice)) == 0) {
                o.setActivityPrice(null);
            }

            Long afterDiscountAmount = o.getAfterDiscountAmount();
            if (Objects.nonNull(afterDiscountAmount) && BigDecimal.ZERO.compareTo(new BigDecimal(afterDiscountAmount)) == 0) {
                o.setAfterDiscountAmount(null);
            }

            String deliveryNoteLineItemNo = o.getDeliveryNoteLineItemNo();
            if (StringUtils.isNotBlank(deliveryNoteLineItemNo) && BigDecimal.ZERO.compareTo(new BigDecimal(deliveryNoteLineItemNo)) == 0) {
                o.setDeliveryNoteLineItemNo(null);
            }

            String afterPodQuality = o.getAfterPodQuality();
            if (StringUtils.isNotBlank(afterPodQuality)) {
                if (BigDecimal.ZERO.compareTo(new BigDecimal(afterPodQuality)) == 0) {
                    o.setAfterPodQuality(null);
                } else {
                    o.setAfterPodQuality(String.valueOf(new BigDecimal(afterPodQuality).setScale(3, RoundingMode.HALF_UP)));
                }
            }

            Long beforeDiscountedAmountOfDeliveryNote = o.getBeforeDiscountedAmountOfDeliveryNote();
            if (Objects.nonNull(beforeDiscountedAmountOfDeliveryNote) && BigDecimal.ZERO.compareTo(new BigDecimal(beforeDiscountedAmountOfDeliveryNote)) == 0) {
                o.setBeforeDiscountedAmountOfDeliveryNote(null);
            }

            Long afterDiscountAmountOfDeliveryNote = o.getAfterDiscountAmountOfDeliveryNote();
            if (Objects.nonNull(afterDiscountAmountOfDeliveryNote) && BigDecimal.ZERO.compareTo(new BigDecimal(afterDiscountAmountOfDeliveryNote)) == 0) {
                o.setAfterDiscountAmountOfDeliveryNote(null);
            }

            String receiptLineItemNo = o.getReceiptLineItemNo();
            if (StringUtils.isNotBlank(receiptLineItemNo) && BigDecimal.ZERO.compareTo(new BigDecimal(receiptLineItemNo)) == 0) {
                o.setReceiptLineItemNo(null);
            }

            Long receiptAmount = o.getReceiptAmount();
            if (Objects.nonNull(receiptAmount) && BigDecimal.ZERO.compareTo(new BigDecimal(receiptAmount)) == 0) {
                o.setReceiptAmount(null);
            }

            Long receiptPrice = o.getReceiptPrice();
            if (Objects.nonNull(receiptPrice) && BigDecimal.ZERO.compareTo(new BigDecimal(receiptPrice)) == 0) {
                o.setReceiptPrice(null);
            }

            String deliveryOrdersQuality = o.getDeliveryOrdersQuality();
            if (StringUtils.isNotBlank(deliveryOrdersQuality)) {
                if (BigDecimal.ZERO.compareTo(new BigDecimal(deliveryOrdersQuality)) == 0) {
                    o.setDeliveryOrdersQuality(null);
                } else {
                    o.setDeliveryOrdersQuality(String.valueOf(new BigDecimal(deliveryOrdersQuality).setScale(3, RoundingMode.HALF_UP)));
                }

            }

            String discountedPrice = o.getDiscountedPrice();
            if (Objects.nonNull(discountedPrice)) {
                if (BigDecimal.ZERO.compareTo(new BigDecimal(discountedPrice)) == 0) {
                    o.setDiscountedPrice(null);
                } else {
                    o.setDiscountedPrice(String.valueOf(new BigDecimal(discountedPrice).divide(new BigDecimal(100), 4, RoundingMode.HALF_UP)));
                }
            }

            Long regularAmountWithRebate = o.getRegularAmountWithRebate();
            if (Objects.nonNull(regularAmountWithRebate) && BigDecimal.ZERO.compareTo(new BigDecimal(regularAmountWithRebate)) == 0) {
                o.setRegularAmountWithRebate(null);
            }

            if (SHIP_RETURN_TYPE.equals(o.getOrderType())) {
                o.setRegularPriceWithRebate(null);
                o.setRegularAmountWithRebate(null);
                o.setAfterDiscountAmount(null);
                o.setDiscountedPrice(null);
                o.setAfterDiscountAmountOfDeliveryNote(null);
            }
        });
    }

    private String packageErrorMessage(List<OrderCompareErrorResult> results) {
        if (CollectionUtils.isEmpty(results)) {
            return null;
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (OrderCompareErrorResult result : results) {
            stringBuilder.append(result.getText())
                    .append(",不匹配")
                    .append(",SAP:")
                    .append(result.getSource())
                    .append(",OTS:")
                    .append(result.getTarget())
                    .append(";");
        }

        return stringBuilder.toString();

    }

    private void buildErrorDetail(Long recordId, Object sapRequest, Object dbExist, String errorMessage) {
        OuiOrderCompareDetail ouiOrderCompareDetail = new OuiOrderCompareDetail();
        ouiOrderCompareDetail.setRecordId(recordId);
        ouiOrderCompareDetail.setCompareResult(errorMessage);
        ouiOrderCompareDetail.setSourceData(JSONObject.toJSONString(sapRequest));
        ouiOrderCompareDetail.setTargetData(JSONObject.toJSONString(dbExist));
        compareDetailService.create(ouiOrderCompareDetail);
    }


}

